package org.u2ml.app.business.impl;

import java.util.List;

import javax.ws.rs.QueryParam;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.u2ml.app.business.UserService;
import org.u2ml.app.domain.User;

@Component
@Transactional
public class UserServiceImpl implements UserService {
	@Autowired
	private SessionFactory sessionFactory;

	@SuppressWarnings("unchecked")
	public List<User> get() {
		List<User> list = sessionFactory.getCurrentSession()
    	.createQuery("from User user")
    	.list();
		return list;
	}
	
	@SuppressWarnings("unchecked")
	public User find(Long oid) {
		List<User> list = sessionFactory.getCurrentSession()
    	.createQuery("from User user where user.oid = :oid")
    	.setParameter("oid",oid)
    	.list();
		return (list.size()==0) ? null : list.get(0);
	}
	
	@SuppressWarnings("unchecked")
	public User findByName(@QueryParam("name") String name) {
		List<User> r = sessionFactory.getCurrentSession()
	        .createQuery("from User user where user.name = :name")
	        .setParameter("name", name)
	        .list();
		if (r.size() == 0) {
			return null;
		} else {
			return r.get(0);
		}
	}
	
	@SuppressWarnings("unchecked")
	public User findByEmail(@QueryParam("email") String email) {
		List<User> r = sessionFactory.getCurrentSession()
	        .createQuery("from User user where user.email = :email")
	        .setParameter("email", email)
	        .list();
		if (r.size() == 0) {
			return null;
		} else {
			return r.get(0);
		}
	}
	
	public User save(User user) {
		sessionFactory.getCurrentSession().save(user);
		return user;
	}
	
	public User update(User user) {
		sessionFactory.getCurrentSession().update(user);
		return  user;
	}
	
	public void delete(User user) {
		sessionFactory.getCurrentSession().delete(user);
	}
}
